<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Api;

use App\Model\Enterprise;
use App\Model\EnterpriseCertification;
use App\Model\User;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Validation\Rule;

#[Controller]
class EnterpriseController
{
    #[Inject]
    protected ValidatorFactoryInterface $validationFactory;

    #[Inject]
    protected RequestInterface $request;

    #[RequestMapping(path: "auth", methods: "post")]
    /**
     * 企业认证
     * @return false|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function auth()
    {
        /** @var User $user */
        $user = auth()->user();
        $enterprise = $user->enterprise;
        if ($enterprise) {
            return self::jsonResponse(400, '您已有企业,请勿重复认证');
        }

        $enterprise = Enterprise::query()->where('code', $this->request->input('code'))->count();
        if ($enterprise) {
            return self::jsonResponse(400, '您申请认证的企业已被他人认证');
        }

        $count = $user->enterpriseCertification()->where('status', 1)->count();
        if ($count) {
            return self::jsonResponse(400, '您有一条待审核认证,请勿重复提交认证');
        }

        $data = $this->validationFactory->make(
            $this->request->all(),
            [
                'name' => 'required',
                'code' => [
                    'required',
                    Rule::unique('enterprise_certification')->where(function ($q) {
                        $q->whereNull('delete_time')->whereIn('status', [1, 2]);
                    })
                ],
                'address' => 'required',
                'mobile' => 'required',
                'img_id' => 'required',
            ],
            [
                'name.required' => '请填写企业名称',
                'code.required' => '请填写统一社会信用代码',
                'code.unique' => '对应统一社会信用代码已被申请认证',
                'address.required' => '请填写地址',
                'mobile.required' => '请填写联系电话',
                'img_id.required' => '请上传营业执照照片'
            ]
        );

        if ($data->fails()) {
            // Handle exception
            $errorMessage = $data->errors()->first();
            return self::jsonResponse(422, $errorMessage);
        }

        $data = $data->validated();

        $auth = new EnterpriseCertification($data);
        $auth->user()->associate($user);
        $auth->save();

        return self::jsonResponse(200, 'success');
    }

    #[RequestMapping(path: "detail", methods: "get")]
    /**
     * 详情
     * @return false|string
     */
    public function detail()
    {
        /** @var User $user */
        $user = auth()->user();
        $enterprise = $user->enterprise;
        if (!$enterprise) {
            $enterprise = $user->enterpriseCertification()->orderByDesc('create_time')->first();
            if (!$enterprise) {
                return self::jsonResponse(200, 'success', []);
            }
        }

        return self::jsonResponse(200, 'success', $enterprise->toApi());
    }

    public static function jsonResponse(int $status = 1, $message = 'success', $data = null, $headerStatus = 200)
    {
        if (is_array($message)) {
            $data = $message;
            $message = 'success';
        }
        if (empty($data)) {
            $data = new class {
            };
        }

        return json_encode(['status' => $status, 'message' => $message, 'data' => $data]);

//        return response()->json(
//            ['status' => $status, 'message' => $message, 'data' => $data],
//            $headerStatus,
//            [],
//            JSON_UNESCAPED_UNICODE
//        );
    }
}
